package com.swq.java.code.chapter13.code24;

public class Machine extends Thread {
    private Counter counter;  //共享数据

    public Machine(Counter counter) {
        this.counter = counter;
        start();  //启动自身线程
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.add();
        }
    }

    public static void main(String args[]) throws InterruptedException {
        Counter counter1 = new Counter();
        Counter counter2 = new Counter();
        counter1.setFriend(counter2);
        counter2.setFriend(counter1);

        Machine machine1 = new Machine(counter1);
        // 主线程sleep一段时间，确保线程1进入同步方法
        Thread.sleep(500);
        Machine machine2 = new Machine(counter2);
    }
}

class Counter {
    private int a;
    private Counter friend;

    public void setFriend(Counter friend) {
        this.friend = friend;
    }

    public synchronized void add() {
        // 在加锁后sleep一段时间（比主线程sleep长），模拟出完全的死锁
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        a++;
        Thread.yield();
        friend.delete();
        System.out.println(Thread.currentThread().getName() + ": add");
    }

    public synchronized void delete() {
        a--;
        System.out.println(Thread.currentThread().getName() + ": delete");
    }
}
